package cn.Leamus;



import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.app.PendingIntent;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.location.LocationManager;
import android.location.Criteria;
import android.provider.Settings;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import java.lang.ClassLoader;
import dalvik.system.DexClassLoader;
import java.lang.reflect.Field;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import android.provider.MediaStore;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;

/*
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
*/


public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity {

    //构造函数
    public MainActivity() {
        m_instance = this;
        Alipay.m_instance = m_instance;

        System.out.println("Qt Java Example By Pleafles");
        Log.i("[java]MainActivity", "MainActivity");
        Log.d("[java]MainActivity", "MainActivity");
    }

    protected void finalize()
    {
        // finalization code here
        Log.d("[java]MainActivity", "finalize");
    }


    //Create函数
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("[java]MainActivity", "onCreate");
        Log.d("[java]MainActivity", "onCreate");

        //checkPermission();
    }



//Toast
    private static final int MSG_TOAST = 1;

    //鹰：貌似可以接受其他线程的消息，在主线程循环中运行
    private static Handler m_handler = new Handler()  //调用Toast 需要用到Handler，要不然无法调用
    {
        @Override
        public void handleMessage(Message msg) {
            Toast toast;
            switch (msg.what) {
            case MSG_TOAST:
                {
                    toast = Toast.makeText(m_instance,(String)msg.obj, Toast.LENGTH_SHORT);
                    toast.show();
                    break;
                }
            };
        }
    };

    //Toast貌似必须运行在主线程里!?
    //一种实现Toast的方法
    public void QMessage(String s)
    {
        Toast toast =  Toast.makeText(this, s, Toast.LENGTH_SHORT);
        toast.show();
    }

    //另一种实现Toast的方法（用Handler）
    public static void makeToast(String s) {
        m_handler.sendMessage(m_handler.obtainMessage(MSG_TOAST, s));
    }




    //获取SDCard路径
    public static String getSdcardPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                        .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
            return sdDir.toString();
        }
        return "";
    }


    //安装APK
    public static void installApk(String filePath, cn.Leamus.MainActivity activity)
    {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        File file = new File(filePath);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        activity.startActivity(intent);
    }



    //有问题!!!
    public static int getNetworkState() {
        ConnectivityManager conMan = (ConnectivityManager) m_instance.getSystemService(Context.CONNECTIVITY_SERVICE);
        return conMan.getActiveNetworkInfo() == null ? 0 : 1;
    }
    /*
    public int getNetworkState1(){
        ConnectivityManager conMan = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return conMan.getActiveNetworkInfo() == null ? 0 : 1;
    }*/

    //开启活动
    public static void launchActivity(String action) {
        m_instance.startActivity(new Intent(action));
    }








//成员变量
    private static MainActivity m_instance;






//检查和请求权限
    public static final int PERMISSIONS_REQUEST_STORAGE = 1;

    //1.检查、异步请求 WRITE_EXTERNAL_STORAGE 权限
    private void checkPermission() {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            PERMISSIONS_REQUEST_STORAGE);
        }
    }

    //2.用户授权后的（requestPermissionsSync） 回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode)
        {
            case PERMISSIONS_REQUEST_STORAGE:
            {
                if (grantResults.length > 0
                                && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                }
                else
                {
                    //Toast.makeText(MainActivity.this,"Please give me storage permission!",Toast.LENGTH_LONG).show();
                    Log.d("[java]MainActivity", "Storage permission CANCEL!");
                }
            }
            default:
                if (grantResults.length > 0
                                && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                }
                else
                {
                    //Toast.makeText(MainActivity.this,"Please give me permission!",Toast.LENGTH_LONG).show();
                     Log.d("[java]MainActivity", "Permission CANCEL!");
                }
        }
        //!!!注意：必须要加上这句，否则requestPermissionsSync的延时会出现问题（无论点击允许还是拒绝，都要等待延时结束）
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }


    /*
    public static PowerManager.WakeLock screen_WakeLock = null;
    public static void screen_KeepWake() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        screen_WakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG");
        screen_WakeLock.acquire();
    }

    public static void screen_ReleaseWake() {
        screen_WakeLock.release();
    }*/

    /*
    public static void mini() {
       m_instance.moveTaskToBack(true);
    }

    public static void moveTaskToFrount() {
        if(!m_instance.isForeground(m_instance.getPackageName())) {
            ActivityManager am = (ActivityManager)m_instance.getSystemService(Context.ACTIVITY_SERVICE);
            am.moveTaskToFront(m_instance.getTaskId(),0);
        }

    }

    private boolean isForeground(String packageName) {

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
*/
}
